<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
            <el-form-item label="车牌号" prop="carNo">
                <el-input v-model="queryParams.carNo" placeholder="请输入车牌号" clearable size="small" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="车型"
                          prop="carModelId">
                <el-select v-model="queryParams.carModelId"
                           clearable
                           @1change="handleQuery">
                    <template v-for="item in configurationList">
                        <el-option :key="item.configurationId"
                                   :label="`${item.modelName} - ${item.modelInfo}`"
                                   :value="item.configurationId"></el-option>
                    </template>
                </el-select>
            </el-form-item> -->
            <el-form-item label="年检时效" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择" clearable @change="handleQuery">
                    <el-option label="有效" :value="1"></el-option>
                    <el-option label="失效" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="车辆状态 " prop="carStatus">
                <el-select v-model="queryParams.carStatus" placeholder="请选择车辆状态" clearable @1change="handleQuery">
                    <template v-for="item in dict.type.car_status">
                        <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['maintenance:insurance:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['maintenance:insurance:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:user:import']">导入</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="insuranceList" @selection-change="handleSelectionChange">
            <el-table-column label="车牌号" align="left" prop="carNo" width="100" />
            <el-table-column label="车架号" align="center" prop="vinNo" />
            <el-table-column label="车辆信息" align="center" prop="carInfo" />
            <el-table-column label="所属门店" align="center" prop="deptName" />
            <el-table-column label="所属租户" align="center" prop="tenantName" />
            <el-table-column label="本次年审时间" align="center" prop="thisTimeInspectionTime" width="150">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.thisTimeInspectionTime, '{y}-{m}-{d}') || '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="下次年审时间" align="center" prop="nextInspectionTime" width="150">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.nextInspectionTime, '{y}-{m}-{d}') || '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="剩余天数" align="right" prop="days" width="100">
                <template slot-scope="{row}">
                    {{row.days}}天
                </template>
            </el-table-column>
            <el-table-column label="车辆状态" align="center" prop="carStatus" width="100">
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.car_status" :value="row.carStatus" />
                </template>
            </el-table-column>
            <el-table-column label="年检状态" align="center" prop="type" width="100">
                <template slot-scope="{row}">
                    <el-tag v-if="row.type==1" style="width:58px" type="primary">已年检</el-tag>
                    <el-tag v-if="row.type==2" style="width:58px" type="danger">未年检</el-tag>
                    <el-tag v-if="row.type==3" style="width:58px" type="warning">预警</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
                <template slot-scope="scope">
                    <template v-if="scope.row.type==1&&scope.row.id">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['maintenance:insurance:edit']">修改</el-button>
                    </template>
                    <template v-else>
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['maintenance:insurance:edit']">年检</el-button>
                    </template>
                    <el-button size="mini" type="text" icon="el-icon-search" @click="hanldeDetail(scope.row)" v-hasPermi="['maintenance:insurance:edit']">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改年检管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1100px" destroy-on-close append-to-body @close="editNowId=null">
            <MmvEditor ref="MmvEditor" v-if="open" :carId="editNowId"></MmvEditor>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="年检详情" append-to-body :visible.sync="showDetail" width="1100px" destroy-on-close>
            <MmvDetail v-if="showDetail" :carId="editNowId" :nowDetail="nowDetail" :status="{1:'已年检',2:'未年检',3:'预警'}[nowDetail.type]"></MmvDetail>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!-- <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listInspection,downloadTemplate, delInspection, addInspection, updateInspection, exportInspection, importTemplate } from "@/api/maintenance/inspection";
import * as planApi from "@/api/plan/plan";
import MmvDetail from './detail.vue';
import MmvEditor from './editor.vue';
import { getToken } from "@/utils/auth";

export default {
    name: "Insurance",
    components: {
        MmvDetail,
        MmvEditor,
    },
    dicts: ['mmv_syType', 'car_status'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 年检管理表格数据
            insuranceList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                carId: null,
                type: null,
                carNo: null,
                vinNo: null,
                carInfo: null,
                compulsoryCompanyId: null,
                compulsoryCompany: null,
                compulsoryNo: null,
                compulsoryStartTime: null,
                compulsoryEndTime: null,
                compulsoryAmount: null,
                compulsoryRemark: null,
                commercialTotalAmount: null,
                insuranceStatus: null,
                isAvailable: null,
                deptId: null,
                tenantId: null,
                carStatus:null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            },
            editNow: null,
            showDetail: false,
            nowDetail: {},
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/maintenance/inspection/import"
            },
            configurationList: [], // 车型业务配置列表
        };
    },
    computed: {
        editNowId() {
            return this.editNow?.carId || 0;
        },
    },
    created() {
        this.getList();
        this.getConfigurationList();
    },
    methods: {
        /**
         * 获取车型业务配置列表
         */
        async getConfigurationList() {
            const result = await planApi.configurationList(this.configurationquery);
            this.configurationList = result.rows || [];
        },
        /** 查询年检管理列表 */
        getList() {
            this.loading = true;
            listInspection(this.queryParams).then(response => {
                this.insuranceList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                carId: null,
                carNo: null,
                vinNo: null,
                carInfo: null,
                compulsoryCompanyId: null,
                compulsoryCompany: null,
                compulsoryNo: null,
                compulsoryStartTime: null,
                compulsoryEndTime: null,
                compulsoryAmount: null,
                compulsoryRemark: null,
                commercialTotalAmount: null,
                insuranceStatus: 0,
                delFlag: null,
                isAvailable: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                deptId: null,
                tenantId: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.carId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.editNow = null;
            this.open = true;
            this.title = "添加年检管理";
        },
        /** 查看详情 */
        hanldeDetail(row) {
            this.editNow = row;
            this.showDetail = true;
            this.nowDetail = row;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.editNow = row;
            this.open = true;
            this.title = "修改年检管理";
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs?.MmvEditor?.emitData((form) => {
                console.log(form)
                if (!form) {
                    return;
                }
                if (this.editNowId&&form.id) {
                    updateInspection(form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.open = false;
                        this.getList();
                    });
                } else {
                    addInspection(form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
                // if (form.type == 1 && form.id) {
                //     updateInspection(form).then(response => {
                //         this.$modal.msgSuccess("修改成功");
                //         this.open = false;
                //         this.getList();
                //     });
                // } else {
                //     addInspection(form).then(response => {
                //         this.$modal.msgSuccess("新增成功");
                //         this.open = false;
                //         this.getList();
                //     });
                // }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.carId || this.ids;
            this.$modal.confirm('是否确认删除数据项？').then(function () {
                return delInspection(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$modal.confirm('是否确认导出所有年检管理数据项？').then(() => {
                this.exportLoading = true;
                return exportInspection(queryParams);
            }).then(response => {
                this.$download.name(response.msg);
                this.exportLoading = false;
            }).catch(() => { });
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "导入";
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
           /* importTemplate().then(response => {
                this.$download.name(response.msg);
,            }); */
			const queryParams = this.queryParams;
			downloadTemplate(queryParams).then(response => {
			    this.$download.name(response.msg);
			});
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
    }
};
</script>
